﻿package net.pezzato.graphics{
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.display.Sprite;
	import flash.display.DisplayObject;
	import flash.filters.DropShadowFilter;
	import flash.events.MouseEvent;
	import net.pezzato.graphics.TitleBar;
	import net.pezzato.graphics.GraphicsEvent;
	import net.pezzato.graphics.Widget;
	public class Window extends Widget {
		private var bg_:Sprite;
		private var titleBar_:TitleBar;
		private var title_:String;
		public function Window(widgetParent:Widget, name:String, x:Number = 0, y:Number = 0, w:Number = 0, h:Number = 0) {
			super(widgetParent, "Window");
			floating = true;
			bg_ = new Sprite();
			title_ = name;
			dispatchChange_ = false;
			rect.x = x;
			rect.y = y;
			rect.width = w;
			rect.height = h;
			drawBg();
			addChild(bg_);
			drawTitleBar();
			titleBar_.addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
			titleBar_.addEventListener(MouseEvent.MOUSE_UP, dropIt);
			addChild(titleBar_);
			drawDropShadow();
			dispatchChange_ = true;
			changed();
		}
		public function centerWindow() {
			dispatchChange_ = false;
			if (parent != null) {
				this.x = (parent.width - this.width) / 2;
				this.y = (parent.height - this.height) / 2;
			}
			dispatchChange_ = true;
		}
		public function close() {
			if (parent != null) {
				parent.removeChild(this);
			}
		}
		override protected function onChange() {
			drawBg();
			drawTitleBar();
		}
		protected function centerX(o:DisplayObject) {
			o.x = bg_.width / 2 - o.width /2;
		}
		protected function centerY(o:DisplayObject) {
			o.y = bg_.height / 2 - o.height /2;
		}
		protected function toTop(o:DisplayObject) {
			o.y = titleBar_.height + 5;
		}
		protected function toBottom(o:DisplayObject) {
			o.y = bg_.height - 10 - o.height;
		}
		protected function toLeft(o:DisplayObject) {
			o.x = 5;
		}
		protected function toRight(o:DisplayObject) {
			o.x = bg_.width - 5 - o.width;
		}
		private function drawTitleBar() {
			if (titleBar_ == null) {
				titleBar_ = new TitleBar(this, title_, rect.width);
				titleBar_.x = 0;
			} else {
				titleBar_.changeWidth(rect.width);
			}
		}
		private function drawBg() {
			bg_.graphics.clear();
			bg_.graphics.lineStyle(4, 0x666666, 0.5, true);
			bg_.graphics.beginFill(0xcccccc, 1);
			bg_.graphics.drawRoundRect(rect.x, rect.y, rect.width, rect.height, 4, 4);
		}
		private function drawDropShadow() {
			var shadow:DropShadowFilter = new DropShadowFilter();
			shadow.distance = 4;
			shadow.blurX = 10;
			shadow.blurY = 10;
			shadow.angle = 45;
			shadow.alpha = 0.5;
			filters = [shadow];
		}
		private function pickUp(event:MouseEvent) {
			this.startDrag();
		}
		private function dropIt(event:MouseEvent) {
			this.stopDrag();
		}
	}
}